package com.myapp.ruyixing.ui;

import java.util.List;

import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
import com.myapp.ruyixing.R;
import com.myapp.ruyixing.http.RYHttpClient;
import com.myapp.ruyixing.http.RYHttpResponseHandler;
import com.myapp.ruyixing.model.ReplyList;
import com.myapp.ruyixing.model.ReplyList.AReply;
import com.myapp.ruyixing.utils.BitmapLruCache;

public class ReplyFragment extends ListFragment {
	
	private RYHttpResponseHandler mHttpResponseHandler = new RYHttpResponseHandler() {

		@Override
		public void onSuccess(Object o) {
			ReplyList data = (ReplyList) o;
			
			if (data != null && data.items != null) {
				MyListAdapter adapter = new MyListAdapter(data.items);
				setListAdapter(adapter);
			}
		}

		@Override
		public void onFailure(Throwable throwable) {
			Toast.makeText(getActivity(), "加载失败",
					Toast.LENGTH_SHORT).show();
		}
	};

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		RYHttpClient.getMyReplyList(getActivity(), mHttpResponseHandler);
	}
	
	private class ViewHolder {
		TextView mTitleView;
		TextView mTimeView;
		TextView mContentView;
		NetworkImageView mAvatarView;
	}
	
	private class MyListAdapter extends ArrayAdapter<AReply> {

		private RequestQueue mQueue;
		private ImageLoader mImageLoader;

		public MyListAdapter(List<AReply> list) {
			super(getActivity(), -1, list);
			mQueue = Volley.newRequestQueue(getActivity());
			mImageLoader = new ImageLoader(mQueue, new BitmapLruCache());
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(getContext()).inflate(
						R.layout.cell_reply, parent, false);

				ViewHolder holder = new ViewHolder();
				holder.mTitleView = (TextView) convertView
						.findViewById(R.id.title);
				holder.mTimeView = (TextView) convertView
						.findViewById(R.id.time);
				holder.mContentView = (TextView) convertView
						.findViewById(R.id.content);
				holder.mAvatarView = (NetworkImageView) convertView
						.findViewById(R.id.avatar);

				convertView.setTag(holder);
			}

			ViewHolder holder = (ViewHolder) convertView.getTag();
			AReply item = getItem(position);

			holder.mTitleView.setText(item.title);
			holder.mContentView.setText("“" + item.replyinfo + "”");
			holder.mTimeView.setText(item.datetime);
			if (!TextUtils.isEmpty(item.avatar)) {
				holder.mAvatarView.setImageUrl(item.avatar, mImageLoader);
			}

			return convertView;

		}
	}
}
